package com.hgyc.mom.system.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hgyc.mom.common.exception.BizException;
import com.hgyc.mom.common.util.CryptoUtils;
import com.hgyc.mom.system.entity.SysUser;
import com.hgyc.mom.system.entity.SysWebToken;
import com.hgyc.mom.system.mapper.SysWebTokenMapper;
import com.hgyc.mom.system.service.SysUserService;
import com.hgyc.mom.system.service.SysWebTokenService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Web令牌 Service业务层实现
 *
 * @author fwj
 * @since 2025-08-08
 */
@Slf4j
@Service
public class SysWebTokenServiceImpl extends ServiceImpl<SysWebTokenMapper, SysWebToken> implements SysWebTokenService {

    @Autowired
    private SysUserService sysUserService;

    @Override
    public void saveToken(SysWebToken sysWebToken) {
        if (sysWebToken.getAppCode() == null || "".equals(sysWebToken.getAppCode())) {
            throw new BizException("应用编码不能为空！");
        }
        String appCode = sysWebToken.getAppCode();
        SysWebToken existToken = getTokenByAppCode(appCode);
        if (existToken != null) {
            throw new BizException(appCode + "已存在不能重复添加！");
        }

        sysWebToken.setSecret(CryptoUtils.encode(sysWebToken.getAppCode()));
        save(sysWebToken);
    }

    private SysWebToken getTokenByAppCode(String appCode) {
        LambdaQueryWrapper<SysWebToken> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysWebToken::getAppCode, appCode);
        return baseMapper.selectOne(queryWrapper, false);
    }

    @Override
    public void updateToken(SysWebToken sysWebToken) {
        // TODO 其他逻辑
        updateById(sysWebToken);
    }

    @Override
    public void removeToken(List<Long> ids) {
        // TODO 其他逻辑
        removeByIds(ids);
    }

    @Override
    public void login(SysWebToken sysWebToken) {
        String appCode = sysWebToken.getAppCode();
        SysWebToken existToken = getTokenByAppCode(appCode);
        if (existToken == null) {
            throw new BizException(appCode + "令牌不存在！");
        }

        Long userId = existToken.getUserId();
        SysUser sysUser = sysUserService.getById(userId);
        if (sysUser == null) {
            throw new BizException("用户不存在，请联系管理员！");
        }
        StpUtil.login(userId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String importData(List<SysWebToken> sysWebTokenList, boolean updateSupport) {
        if (sysWebTokenList == null || sysWebTokenList.isEmpty()) {
            throw new IllegalArgumentException("导入数据不能为空");
        }

        try {
            if (updateSupport) {
                // TODO 实现更新已有数据的导入逻辑
                return "更新导入成功，共导入 " + sysWebTokenList.size() + " 条数据";
            } else {
                // TODO 实现不更新已有数据的导入逻辑
                return "新增导入成功，共导入 " + sysWebTokenList.size() + " 条数据";
            }
        } catch (Exception e) {
            log.error("Web令牌 导入失败", e);
            throw new BizException("Web令牌 导入失败：" + e.getMessage());
        }
    }
}
